﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace Databases
{
    /// <summary>
    /// The Database Form code
    /// </summary>
    public partial class DatabaseMainForm : Form
    {
        /// <summary>
        /// Add a DAL object
        /// </summary>
        private DAL data;
        /// <summary>
        /// Add a DataAccessQueriesReader
        /// </summary>
        private DataAccessQueriesReader qr;

        // for tab loading
        private bool firstTransferTabLoad;
        private bool firstLoadOrderTab;

        public DatabaseMainForm()
        {
            InitializeComponent();
            data = new DAL();
            qr = new DataAccessQueriesReader();
            //Load the locations
            LoadLocations();
            getWeaponInventory();
            firstTransferTabLoad = true;
            firstLoadOrderTab = true;
        }

        /// <summary>
        /// Loads the locations into the Locations combo box on the inventory Tab.
        /// </summary>
        public void LoadLocations()
        {
            DataSet ds = data.getDataSet(qr.getSelect("getLocations"));
            cmbLocations.DataSource = ds.Tables[0].DefaultView;
            cmbLocations.DisplayMember = "LocationName";
            cmbLocations.ValueMember = "LocationID";
            cmbLocations.SelectedValue = 1;
        }

        private void cmbLocation_OnChange(object sender, EventArgs e)
        {
            getWeaponInventory();
        }

        private void getWeaponInventory()
        {
            List<OleDbParameter> parameters = new List<OleDbParameter>();
            OleDbParameter param = new OleDbParameter("@LocationID", cmbLocations.SelectedValue);
            parameters.Add(param);

            DataSet ds = data.getDataSetWithParameters(qr.getSelect("getInvByLocID"), parameters);
            dgvInventoryWeapons.DataSource = ds.Tables[0];
        }

        private void pageTab_Selected(object sender, TabControlEventArgs e)
        {
            TabControl t = sender as TabControl;
            switch (t.SelectedIndex)
            {
                case 1:
                    if (firstLoadOrderTab)
                    {
                        LoadOrdersTab();
                        firstLoadOrderTab = false;
                    }
                    break;
                case 2:
                    if (firstTransferTabLoad)
                    {
                        LoadTransfersTab();
                        firstTransferTabLoad = false;
                    }
                    break;
                default:
                    break;
            }
        }

        private void LoadTransfersTab()
        {
            LoadTransferFrom();
            LoadAvailableVehicles();
            LoadTransferTo();
        }

        private void LoadTransferFrom()
        {
            DataSet ds = data.getDataSet(qr.getSelect("getLocations"));
            cmbFrom.DataSource = ds.Tables[0].DefaultView;
            cmbFrom.DisplayMember = "LocationName";
            cmbFrom.ValueMember = "LocationID";
            cmbFrom.SelectedValue = 1;
        }

        private void LoadTransferTo()
        {
            List<OleDbParameter> parameters = new List<OleDbParameter>();
            OleDbParameter param = new OleDbParameter("@LocationID", cmbFrom.SelectedValue);
            parameters.Add(param);
            DataSet ds = data.getDataSetWithParameters(qr.getSelect("getLocationsWOPassedID"), parameters);
            cmbTo.DataSource = ds.Tables[0].DefaultView;
            cmbTo.DisplayMember = "LocationName";
            cmbTo.ValueMember = "LocationID";
            cmbTo.SelectedIndex = 0;
        }

        private void LoadAvailableVehicles()
        {
            List<OleDbParameter> parameters = new List<OleDbParameter>();
            OleDbParameter param = new OleDbParameter("@LocationID", cmbFrom.SelectedValue);
            parameters.Add(param);
            DataSet ds = data.getDataSetWithParameters(qr.getSelect("getVehiclesByLocationID"), parameters);
            lstVehiclesAvailable.DataSource = ds.Tables[0].DefaultView;
            lstVehiclesAvailable.DisplayMember = "VehicleString";
            lstVehiclesAvailable.ValueMember = "VehicleID";
        }

        private void cmbFrom_SelectedValueChanged(object sender, EventArgs e)
        {
            if (!firstTransferTabLoad)
            {
                LoadAvailableVehicles();
                LoadTransferTo();
            }
            else
            {
                firstTransferTabLoad = false;
            }
        }

        private void btnDoTransfer_Click(object sender, EventArgs e)
        {
            DoTransfer(lstVehiclesAvailable.SelectedItems);
        }

        private void DoTransfer(ListBox.SelectedObjectCollection items)
        {
            foreach (DataRowView d in items)
            {
                List<OleDbParameter> parameters = new List<OleDbParameter>();
                parameters.Add(new OleDbParameter("@LocationID", cmbTo.SelectedValue));
                parameters.Add(new OleDbParameter("@VehicleID", Convert.ToInt32(d["VehicleID"])));
                
                int rows = data.updateData(qr.getUpdate("updateVehicleLocation"), parameters);
            }

            LoadAvailableVehicles();
        }

        private void btnUseItem_Click(object sender, EventArgs e)
        {
            UseItem();
        }

        private void UseItem()
        {
            if (nudQuantityToUse.Value > 0)
            {
                int locationID = Convert.ToInt32(cmbUseLocation.SelectedValue);
                int currentQty = Convert.ToInt32(txtQtyAvailable.Text);
                int numToUse = Convert.ToInt32(nudQuantityToUse.Value);
                int restockValue = Convert.ToInt32((cmbUseItem.Tag as DataRowView)["RestockValue"]);
                int weaponID = Convert.ToInt32((cmbUseItem.Tag as DataRowView)["WeaponID"]);
                int locationWeaponID = Convert.ToInt32(cmbUseItem.SelectedValue);

                List<OleDbParameter> parameters = new List<OleDbParameter>();
                parameters.Add(new OleDbParameter("@LocationWeaponID", locationWeaponID));
                parameters.Add(new OleDbParameter("@Quantity", numToUse));
                // not sure what is happening but the update doesn't really work when I use the params
                // in the method which is strange because it works in other places.
                string query = qr.getUpdate("updateLocationWeapon");

                foreach (OleDbParameter p in parameters)
                {
                    query = query.Replace(p.ParameterName, Convert.ToString(p.Value));
                }
                parameters.Clear();
                int rowsAffected = data.updateData(query, parameters);

                // if we have dropped to a value below or equal to the restock of this
                // item then automatically generate an order for it.
                if (currentQty - numToUse <= restockValue && rowsAffected > 0)
                {
                    int amountForOrder = (int)(restockValue * .20) + numToUse;
                    PlaceOrder(amountForOrder, weaponID, locationID);
                    LoadOrders();
                }

                LoadItemToUse();
            }
        }

        private void PlaceOrder(int amount, int weaponID, int locationID)
        {
            List<OleDbParameter> parameters = new List<OleDbParameter>();
            parameters.Add(new OleDbParameter("LocationID", locationID));

            NonQueryResult nrq = data.insertData(qr.getInsert("InsertLocationOrderMaster"), parameters, qr.getSelect("Identity"));

            // we should get an identity with the master insert so that we can
            // insert it in the detail table.
            if (nrq.Identity > 0)
            {
                parameters.Clear();
                parameters.Add(new OleDbParameter("@OrderID", nrq.Identity));
                parameters.Add(new OleDbParameter("@WeaponID", weaponID));
                parameters.Add(new OleDbParameter("@Quantity", amount));
                // no identity is needed with this insert so the identityQuery parameter is passed
                // an empty string.
                nrq = data.insertData(qr.getInsert("InsertLocationOrderDetail"), parameters, string.Empty);
            }
        }

        private void LoadOrdersTab()
        {
            LoadUseLocation();
            LoadItemToUse();
            LoadOrders();
        }

        private void LoadOrders()
        {
            DataSet ds = data.getDataSet(qr.getSelect("getOrders"));
            dgvItemsOnOrder.DataSource = ds.Tables[0];
        }

        private void LoadItemToUse()
        {
            List<OleDbParameter> parameters = new List<OleDbParameter>();
            parameters.Add(new OleDbParameter("@LocationID", cmbUseLocation.SelectedValue));
            DataSet ds = data.getDataSetWithParameters(qr.getSelect("getWeaponsByLocationID"), parameters);
            cmbUseItem.DataSource = ds.Tables[0].DefaultView;
            cmbUseItem.DisplayMember = "WeaponName";
            cmbUseItem.ValueMember = "LocationWeaponID";
            cmbUseItem.SelectedIndex = 0;

            setOtherItemData();
        }

        private void setOtherItemData()
        {
            cmbUseItem.Tag = cmbUseItem.SelectedItem;
            DataRowView drv = (DataRowView)cmbUseItem.Tag;
            txtQtyAvailable.Text = Convert.ToString(drv["Quantity"]);
            nudQuantityToUse.Maximum = Convert.ToInt32(drv["Quantity"]);
            nudQuantityToUse.Value = 0;
        }

        private void LoadUseLocation()
        {
            DataSet ds = data.getDataSet(qr.getSelect("getLocations"));
            cmbUseLocation.DataSource = ds.Tables[0].DefaultView;
            cmbUseLocation.DisplayMember = "LocationName";
            cmbUseLocation.ValueMember = "LocationID";
            cmbUseLocation.SelectedValue = 1;
        }

        private void cmbUseLocation_SelectedValueChanged(object sender, EventArgs e)
        {
            if (!firstLoadOrderTab)
            {
                LoadItemToUse();
            }
            else
            {
                firstLoadOrderTab = false;
            }
        }

        private void cmbUseItem_SelectedValueChanged(object sender, EventArgs e)
        {
            setOtherItemData();
        }
    }
}
